package eraserhead.boundary;

import java.awt.Rectangle;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.JPanel;
import javax.swing.JTextField;

import eraserhead.controller.SetChoiceController;
import eraserhead.entity.Decision;
import eraserhead.entity.Line;

/**
 * Panel to contain the choices {@link JTextField} objects.
 */
public class ChoicePanel extends JPanel {
	private static final long serialVersionUID = -4710042160983397823L;

	Decision model;
	
	JTextField[] choices;
	
	boolean canGiveChoice = true;
	
	/**
	 * Create a new {@link ChoicePanel}
	 * @param model {@link Decision} model associated with this {@link ChoicePanel}
	 */
	public ChoicePanel(Decision model) {
		this.model = model;
		initComponents();
	}
	
	public void initComponents() {
		setLayout(null);
		
		/** Chooses a location for the JTextFields.*/
		int choicesPanelWidth = 448;
		choices = new JTextField[model.getNumUsers()];
		for (int i = 0; i < model.getNumUsers(); i++) {
			int s = (choicesPanelWidth - 60) / (model.getNumUsers() - 1);
            choices[i] = new JTextField ();
            choices[i].setBounds(new Rectangle(i * s, 10, 60, 20));
            add(choices[i]);
            
            final int position = i;
            choices[position].addActionListener(new ActionListener() {
				@Override
				public void actionPerformed(ActionEvent arg0) {
					new SetChoiceController(model, ChoicePanel.this, position).process();
				}
			});
		}	
        for (Line l : model.getLines()) {
        	choices[l.getPosition()].setText(l.getChoice());
        }
	}
	
	/**
	 * Sets a specific choice text
	 * @param position Position in the {@link Decision} of the choice
	 * @param choice String representation of the choice to set
	 */
	public void setChoiceField(int position, String choice) {
		choices[position].setText(choice);
	}
	
	/**
	 * Gets the {@link JTextField} for the choice at position index
	 * @param index Position of the choice {@link JTextField} to get
	 * @return {@link JTextField} for choice at index
	 */
	public JTextField getChoiceField(int index) {
		return choices[index];
	}

	/**
	 * Determines if the user can give their choice
	 * @return True for the ability to give a choice, false otherwise
	 */
	public boolean getCanGiveChoice() {
		return canGiveChoice;
	}

	/**
	 * Sets the ability of a user to give their choice
	 * @param canGiveChoice True to allow giving choices, false otherwise
	 */
	public void setCanGiveChoice(boolean canGiveChoice) {
		this.canGiveChoice = canGiveChoice;
	}
	
}